import React, { useState, useRef, useEffect } from 'react';
import { Modal, ModalProps } from 'antd';
import styles from './index.module.css';

interface DraggableModalProps extends ModalProps {
  dragHandle?: string; // 拖拽手柄的 CSS 选择器
  initialPosition?: { x: number; y: number }; // 初始位置
  bounds?: { left: number; top: number; right: number; bottom: number }; // 拖拽边界
}

const DraggableModal: React.FC<DraggableModalProps> = ({
  children,
  dragHandle = '.ant-modal-header', // 默认使用 modal 头部作为拖拽手柄
  initialPosition,
  bounds,
  ...modalProps
}) => {
  const [position, setPosition] = useState(initialPosition || { x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const modalRef = useRef<HTMLDivElement>(null);
  const isDraggingRef = useRef(false);

  console.log('draggableModalWrap 类名:', styles.draggableModalWrap);
  console.log('draggableModal 类名:', styles.draggableModal);

  // 计算初始位置（居中显示）
  useEffect(() => {
    if (!initialPosition && modalProps.open) {
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;
      const modalWidth = 1200; // 默认宽度，实际会从 props 中获取
      const modalHeight = 600; // 估算高度
      
      const centerX = Math.max(0, (windowWidth - modalWidth) / 2);
      const centerY = Math.max(0, (windowHeight - modalHeight) / 2);
      
      setPosition({ x: centerX, y: centerY });
      
      // 等待 DOM 渲染完成后直接设置位置
      const timer = setTimeout(() => {
        const modalElement = document.querySelector(`.${styles.draggableModalWrap} .ant-modal`) as HTMLElement;
        if (modalElement) {
          modalElement.style.position = 'fixed';
          modalElement.style.top = `${centerY}px`;
          modalElement.style.left = `${centerX}px`;
          modalElement.style.margin = '0';
          console.log('设置初始位置:', { x: centerX, y: centerY });
        }
      }, 100);
      
      return () => clearTimeout(timer);
    }
  }, [initialPosition, modalProps.open]);

  // 处理鼠标按下事件
  const handleMouseDown = (e: Event) => {
    const mouseEvent = e as MouseEvent;
    // 检查是否点击了拖拽手柄
    console.log('dragHandle', dragHandle);
    const target = e.target as HTMLElement;
    const dragHandleElement = document.querySelector(`.${styles.draggableModalWrap} ${dragHandle}`);
    
    // 调试信息
    console.log('Mouse down event:', {
      target: target.tagName,
      dragHandle: dragHandle,
      dragHandleElement: !!dragHandleElement,
      contains: dragHandleElement?.contains(target),
      clientX: mouseEvent.clientX,
      clientY: mouseEvent.clientY
    });
    
    if (!dragHandleElement || !dragHandleElement.contains(target)) {
      console.log('未点击拖拽手柄，不触发拖拽');
      return;
    }

    mouseEvent.preventDefault();
    mouseEvent.stopPropagation();
    setIsDragging(true);
    isDraggingRef.current = true;
    
    const rect = (dragHandleElement as HTMLElement).closest('.ant-modal')?.getBoundingClientRect();
    if (!rect) {
      console.log('未获取到模态框的边界信息');
      return;
    }
    console.log('获取到的模态框边界信息:', rect);
    setDragOffset({
      x: mouseEvent.clientX - rect.left,
      y: mouseEvent.clientY - rect.top
    });
    console.log('设置的拖拽偏移量:', { x: mouseEvent.clientX - rect.left, y: mouseEvent.clientY - rect.top });
  };

  // 处理鼠标移动事件
  const handleMouseMove = (e: MouseEvent) => {
    if (!isDraggingRef.current) {
      console.log('未处于拖拽状态，不处理鼠标移动事件');
      return;
    }

    const newX = e.clientX - dragOffset.x;
    const newY = e.clientY - dragOffset.y;
    console.log('计算的新位置:', { newX, newY });
    
    // 应用边界限制
    let finalX = newX;
    let finalY = newY;
    
    if (bounds) {
      const modalElement = document.querySelector(`.${styles.draggableModalWrap} .ant-modal`);
      if (!modalElement) {
        console.log('边界模式下未获取到模态框元素');
        return;
      }
      const modalRect = modalElement.getBoundingClientRect();
      finalX = Math.max(bounds.left, Math.min(bounds.right - modalRect.width, newX));
      finalY = Math.max(bounds.top, Math.min(bounds.bottom - modalRect.height, newY));
      console.log('边界模式下的最终位置:', { finalX, finalY });
    } else {
      // 默认边界：不能拖出屏幕
      const modalElement = document.querySelector(`.${styles.draggableModalWrap} .ant-modal`);
      if (!modalElement) {
        console.log('默认模式下未获取到模态框元素');
        return;
      }
      const modalRect = modalElement.getBoundingClientRect();
      finalX = Math.max(0, Math.min(window.innerWidth - modalRect.width, newX));
      finalY = Math.max(0, Math.min(window.innerHeight - modalRect.height, newY));
      console.log('默认模式下的最终位置:', { finalX, finalY });
    }
    
    // 直接设置 DOM 元素位置
    const modalElement = document.querySelector(`.${styles.draggableModalWrap} .ant-modal`) as HTMLElement;
    if (modalElement) {
      modalElement.style.position = 'fixed';
      modalElement.style.top = `${finalY}px`;
      modalElement.style.left = `${finalX}px`;
      modalElement.style.margin = '0';
      console.log('直接设置 DOM 元素位置:', { x: finalX, y: finalY });
    } else {
      console.log('未找到 Modal 元素，无法设置位置');
    }
    
    setPosition({ x: finalX, y: finalY });
    console.log('设置的新位置:', { x: finalX, y: finalY });
  };

  // 处理鼠标松开事件
  const handleMouseUp = () => {
    console.log('鼠标松开，结束拖拽');
    setIsDragging(false);
    isDraggingRef.current = false;
  };

  // 绑定拖拽事件到拖拽手柄
  useEffect(() => {
    if (!modalProps.open) return;

    // 等待 DOM 渲染完成
    const timer = setTimeout(() => {
      const dragHandleElement = document.querySelector(`.${styles.draggableModalWrap} ${dragHandle}`);
      if (dragHandleElement) {
        console.log('找到拖拽手柄，绑定事件:', dragHandleElement);
        dragHandleElement.addEventListener('mousedown', handleMouseDown);
        
        return () => {
          dragHandleElement.removeEventListener('mousedown', handleMouseDown);
        };
      } else {
        console.log('未找到拖拽手柄元素:', `.${styles.draggableModalWrap} ${dragHandle}`);
      }
    }, 100);

    return () => clearTimeout(timer);
  }, [modalProps.open, dragHandle]);

  // 添加全局事件监听器
  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      
      return () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };
    }
  }, [isDragging, dragOffset, bounds]);

  // 处理 ESC 键关闭
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && modalProps.open) {
        modalProps.onCancel?.(e as any);
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [modalProps.open, modalProps.onCancel]);

  return (
    <Modal
      {...modalProps}
      style={{
        position: 'fixed',
        top: position.y,
        left: position.x,
        margin: 0,
        maxHeight: '90vh',
        overflow: 'auto',
        ...modalProps.style
      }}
      wrapClassName={styles.draggableModalWrap}
      className={`${styles.draggableModal} ${modalProps.className || ''}`}
    >
      {children}
    </Modal>
  );
};

export default DraggableModal;